from typing import Optional, Tuple
from PyQt5.QtCore import Qt, QObject, pyqtSignal
from PyQt5.QtGui import QClipboard
from PyQt5.QtWidgets import QApplication

class TextCapture(QObject):
    """文本捕获类，负责跨应用文本选择功能"""
    text_captured = pyqtSignal(str)  # 文本捕获信号
    
    def __init__(self):
        super().__init__()
        # 确保QApplication实例已创建
        if not QApplication.instance():
            self.app = QApplication([])
        self.clipboard = QApplication.clipboard()
        self.previous_text = self.clipboard.text()
        self.is_monitoring = False
        
        # 连接剪贴板信号
        self.clipboard.dataChanged.connect(self._on_clipboard_change)
    
    def start_monitoring(self) -> None:
        """开始监听文本选择"""
        self.is_monitoring = True
        self.previous_text = self.clipboard.text()
    
    def stop_monitoring(self) -> None:
        """停止监听文本选择"""
        self.is_monitoring = False
    
    def _on_clipboard_change(self) -> None:
        """剪贴板内容变化回调"""
        if not self.is_monitoring:
            return
            
        current_text = self.clipboard.text()
        if current_text and current_text != self.previous_text:
            self.text_captured.emit(current_text)
            self.previous_text = current_text
    
    def get_selected_text(self) -> Optional[str]:
        """获取当前选中的文本"""
        # 保存当前剪贴板内容
        original = self.clipboard.text()
        
        # 模拟复制操作
        QApplication.keyboardModifiers()
        QApplication.keyPress(Qt.Key_Control)
        QApplication.keyPress(Qt.Key_C)
        QApplication.keyRelease(Qt.Key_C)
        QApplication.keyRelease(Qt.Key_Control)
        
        # 获取选中文本
        selected = self.clipboard.text()
        
        # 恢复原始剪贴板内容
        self.clipboard.setText(original)
        
        return selected if selected != original else None
    
    def get_cursor_position(self) -> Tuple[int, int]:
        """获取当前光标位置"""
        cursor = QApplication.desktop().cursor().pos()
        return cursor.x(), cursor.y()